202.オブジェクトベースの2キャラ(CRAZY)

オブジェクトを使っても、2種類のキャラでは関数の重複が発生します。

p5.js oop
Learning OOP Object Oriented Programming

オブジェクトを使って2種類のキャラを管理しています。

改善点

  • データは objobj2 にまとまっている
  • 変数の管理は102より分かりやすい

まだ残る問題: 関数の重複

function update() { obj.x += obj.xSpeed; ... }
function update2() { obj2.x += obj2.xSpeed; ... }

オブジェクトでデータはまとめられましたが、処理(関数)はまだ重複しています。

オブジェクトの限界

オブジェクト = データのまとまり

データ管理は改善されましたが、処理(関数)をまとめる機能がありません。

次の203で、配列と組み合わせた場合も見てみましょう。

View Source Code

let W, H, PW, PH
const PADDING_RATIO = 0.2
const MAX_SPEED = 10

let obj;
let obj2;

function prepare() {
  obj = {
    x: random(width),
    y: random(height),
    xSpeed: (Math.random() - 0.5) * MAX_SPEED,
    ySpeed: (Math.random() - 0.5) * MAX_SPEED,
    acceleration: 0.1,
  };
}

function prepare2() {
  obj2 = {
    x: random(width),
    y: random(height),
    xSpeed: (Math.random() - 0.5) * MAX_SPEED,
    ySpeed: (Math.random() - 0.5) * MAX_SPEED,
    acceleration: 0.1,
  };
}


function update() {
  obj.x += obj.xSpeed;
  obj.y += obj.ySpeed;

  if (obj.x < 0 + PW) {
    obj.xSpeed += obj.acceleration;
  } else if (obj.x > W - PW) {
    obj.xSpeed -= obj.acceleration;
  }
  
  if (obj.y < 0 + PH) {
    obj.ySpeed += obj.acceleration;
  } else if (obj.y > H - PH) {
    obj.ySpeed -= obj.acceleration;
  }
}

function update2() {
  obj2.x += obj2.xSpeed;
  obj2.y += obj2.ySpeed;

  if (obj2.x < 0 + PW) {
    obj2.xSpeed += obj2.acceleration;
  } else if (obj2.x > W - PW) {
    obj2.xSpeed -= obj2.acceleration;
  }
  
  if (obj2.y < 0 + PH) {
    obj2.ySpeed += obj.acceleration;
  } else if (obj2.y > H - PH) {
    obj2.ySpeed -= obj2.acceleration;
  }
}


function display() {
  stroke(0);
  fill(0);
  ellipse(obj.x, obj.y, 10, 10);
  text(["1:", Math.floor(obj.x), Math.floor(obj.y)], obj.x + 10, obj.y + 10);
}


function display2() {
  stroke(0);
  fill(0);
  rectMode(CENTER)
  rect(obj2.x, obj2.y, 10, 10);
  text(["2:", Math.floor(obj2.x), Math.floor(obj2.y)], obj2.x + 20, obj2.y + 20);
}


// main

function setup() {
  createCanvas(W = windowWidth, H = windowHeight);
  PW = W * PADDING_RATIO
  PH = H * PADDING_RATIO

  prepare();
  prepare2();
}

function draw() {
  background(255);

  update();
  update2();
  
  display();
  display2();
}